/*
 * Copyright (C) 2009 Show SMS open source project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bydavy.android.showsms.model;

//~--- non-JDK imports --------------------------------------------------------

import android.content.Context;

import android.os.Bundle;

import android.telephony.gsm.SmsMessage;

//~--- classes ----------------------------------------------------------------

public class SimpleMessageFactory {
    //~--- constructors -------------------------------------------------------

    private SimpleMessageFactory() {}

    //~--- methods ------------------------------------------------------------

    public static SimpleMessage extract(Bundle bundle, Context context) throws Exception {
        SimpleMessage aMessage = null;

        if (bundle != null) {
            Object[] pdus         = (Object[]) bundle.get("pdus");
            SmsMessage[] messages = new SmsMessage[pdus.length];
            StringBuffer body     = new StringBuffer();

            for (int i = 0; i < pdus.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                body.append(messages[i].getMessageBody());
            }

            if (messages.length == 0) {
                throw new Exception("No message in this bundle");
            }

            String phoneNumber = messages[0].getDisplayOriginatingAddress();
            long timeStamp     = System.currentTimeMillis();

            return new SimpleMessage(phoneNumber, body.toString(), timeStamp);
        }

        return aMessage;
    }
}
